package com.roger.comm;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.io.FilenameUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * 索引管理
 * @author luoweiyi
 */
public class LuceneHolder {

	private Analyzer defaultAnalyzer;

	private String indexPath;

	private Directory dir;

	public LuceneHolder(Analyzer analyzer, String indexPath) {
		this.defaultAnalyzer = analyzer;
		try {
			this.indexPath = initIndexPath(indexPath);
		} catch (IOException e) {
			System.out.println("The indexPath:" + indexPath + " can not use!!!");
		}
	}

	private String initIndexPath(String indexPath) throws IOException {
		indexPath = FilenameUtils.normalize(indexPath);
		File file = new File(indexPath);
		if (!file.exists() || !file.isDirectory()) throw new FileNotFoundException(indexPath);
		if (!indexPath.endsWith(File.separator)) indexPath += File.separator;
		return indexPath;
	}

	private IndexWriter getWriter() throws IOException {
		Directory dir = FSDirectory.open(new File(indexPath));
		IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, this.defaultAnalyzer);
		config.setOpenMode(OpenMode.CREATE_OR_APPEND);
		return new IndexWriter(dir, config);
	}

	public static void main(String[] args) {

	}

}
